<template>
  <div class="add-card">
    <header class="add-header">
      <el-page-header
        :content="id ? '编辑月卡' : '增加月卡'"
        @back="$router.back()"
      />
    </header>
    <main class="add-main">
      <div class="form-container">
        <div class="title">车辆信息</div>
        <div class="form">
          <el-form
            ref="cardForm"
            label-width="100px"
            :model="cardForm"
            :rules="cardrules"
          >
            <el-form-item label="车主姓名" prop="personName">
              <el-input v-model="cardForm.personName" />
            </el-form-item>
            <el-form-item label="联系方式" prop="phoneNumber">
              <el-input v-model="cardForm.phoneNumber" />
            </el-form-item>
            <el-form-item label="车辆号码" prop="carNumber">
              <el-input v-model="cardForm.carNumber" />
            </el-form-item>
            <el-form-item label="车辆品牌" prop="carBrand">
              <el-input v-model="cardForm.carBrand" />
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="form-container">
        <div class="title">最新一次月卡缴费信息</div>
        <div class="form">
          <el-form
            ref="feeForm"
            label-width="100px"
            :model="feeForm"
            :rules="cardrules"
          >
            <el-form-item label="有效日期" prop="payTime">
              <!-- 使用format指定输入框的格式；使用value-format指定绑定值的格式 -->
              <el-date-picker
                v-model="feeForm.payTime"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
              />
            </el-form-item>
            <el-form-item label="支付金额" prop="paymentAmount">
              <el-input v-model="feeForm.paymentAmount" />
            </el-form-item>
            <el-form-item label="支付方式" prop="paymentMethod">
              <el-select v-model="feeForm.paymentMethod">
                <el-option
                  v-for="item in paymentList"
                  :key="item.value"
                  :value="item.value"
                  :label="item.title"
                />
              </el-select>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button @click="resetForm">重置</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </div>
    </footer>
  </div>
</template>

<script>
import { addCardAPI, cardDetailAPI, editCardAPI } from '@/api/card'
export default {
  name: 'AddMonthCard',
  data () {
    return {
      cardForm: {
        personName: '张三',
        phoneNumber: '13000000000',
        carNumber: '京A11111',
        carBrand: 'bilibili'
      },
      feeForm: {
        // cardStartDate: '',
        // cardEndDate: '',
        // 默认表单显示格式为2025-05-22
        // 默认控制台输出格式为Thu May 22 2025 00:00:00 GMT+0800 (中国标准时间)，后被value-format属性修改为2025-05-22格式
        payTime: [], // 得到一个长度为2的数组，数组的第一项为开始时间，第二项为结束时间
        paymentAmount: '100',
        paymentMethod: ''
      },
      cardrules: {
        // 非空校验即可
        personName: [
          {
            required: true,
            message: '车主姓名不得为空',
            trigger: 'blur'
          }
        ],
        phoneNumber: [
          {
            required: true,
            message: '联系方式不得为空',
            trigger: 'blur'
          },
          // 联系方式有格式要求/^1[3-9]\d{9}$/
          // 正则校验
          {
            pattern: /^1[3-9]\d{9}$/,
            message: '手机号格式不对',
            trigger: 'blur'
          }
        ],
        carNumber: [
          {
            required: true,
            message: '车辆号码不得为空',
            trigger: 'blur'
          },
          // 车辆号码有格式要求/^[\u4E00-\u9FA5][\da-zA-Z]{6}$/
          // 自定义校验
          {
            validator: this.validatorCarNumber,
            trigger: 'blur'
          }
        ],
        carBrand: [
          {
            required: true,
            message: '车辆品牌不得为空',
            trigger: 'blur'
          }
        ],
        payTime: [
          // 日期框写不写触发事件trigger都行
          {
            required: true,
            message: '请选择支付时间'
          }
        ],
        paymentAmount: [
          {
            required: true,
            message: '支付金额不得为空',
            trigger: 'blur'
          }
        ],
        paymentMethod: [
          {
            required: true,
            message: '支付方式不得为空',
            trigger: 'change' // 下拉框得用change而不是blur
          }
        ]
      },
      paymentList: [
        { title: '支付宝', value: 'Alipay' },
        { title: '微信', value: 'WeChat' },
        { title: '线下', value: 'Cash' }
      ]
    }
  },
  computed: {
    // 既然反复会使用到路径参数id，那可以将其封装为计算属性，方便以后调用
    id () {
      return this.$route.query.id
    }
  },
  created () {
    // 通过是否有id来判断是添加操作还是编辑操作
    // 存在id说明是编辑操作，允许发送获取编辑页月卡详情请求
    if (this.id) {
      this.cardDetail()
    }
  },
  methods: {
    // 车牌号的自定义校验
    validatorCarNumber (rule, value, callback) {
      // rule表示要验证的规则，一般用不上；value表示输入值；callback回调，不管成功还是失败都要调用
      const plateNumberRegex = /^[\u4E00-\u9FA5][\da-zA-Z]{6}$/
      // value值是否符合正则plateNumberRegex
      if (plateNumberRegex.test(value)) {
        callback()
      } else {
        callback(new Error('车牌号格式不对'))
      }
    },
    // 提交
    submit () {
      // console.log(this.$refs.cardForm) // 可以看到输出结果携带有validate方法
      // 串行校验，先校验第一个表单，再校验第二个表单
      this.$refs.cardForm.validate(flag => {
        if (!flag) return
        this.$refs.feeForm.validate(async flag => {
          if (!flag) return
          const data = {
            ...this.cardForm,
            ...this.feeForm,
            cardStartDate: this.feeForm.payTime[0],
            cardEndDate: this.feeForm.payTime[1]
          }
          // 接口做了校验，不允许有多余字段存在，得想办法把payTime去掉
          delete data.payTime
          // console.log(data)
          // carInfoId和rechargeId字段是由获取编辑页月卡详情接口取得的，只有编辑操作才会触发这个接口，两个表单里才会有这2个字段，data里才会有这2个键名
          // 添加操作的data是不会有carInfoId和rechargeId这2个字段的，所以不影响添加操作
          if (this.id) {
            const res = await editCardAPI(data)
            console.log(res)
            this.$message.success('修改成功')
          } else {
            const res = await addCardAPI(data)
            console.log(res)
            this.$message.success('添加成功')
          }
          this.$router.back()
        })
      })
    },
    // 重置表单
    resetForm () {
      // resetFields方法只能重置加了prop表单域的内容，没加的想要清空只能手动清空
      this.$refs.cardForm.resetFields()
      this.$refs.feeForm.resetFields()
    },
    // 获取编辑页月卡详情
    async cardDetail () {
      // console.log(this.id)
      const res = await cardDetailAPI(this.id)
      console.log(res)
      // 解构对象
      const {
        personName,
        phoneNumber,
        carNumber,
        carBrand,
        cardStartDate,
        cardEndDate,
        paymentAmount,
        paymentMethod,
        carInfoId, // 月卡车辆id
        rechargeId // 缴费信息id
      } = res.data
      // 回显数据
      this.cardForm = {
        personName,
        phoneNumber,
        carNumber,
        carBrand,
        carInfoId // 临时增加的属性
      }
      this.feeForm = {
        payTime: [cardStartDate, cardEndDate],
        paymentAmount,
        paymentMethod,
        rechargeId // 临时增加的属性
      }
    }
  }
}
</script>

<style scoped lang="scss">
.add-card {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    align-items: center;
    padding: 0 20px;
    height: 64px;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }
      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    background: #f4f6f8;
    padding: 20px 130px;

    .form-container {
      background-color: #fff;

      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }

      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;

        .el-form {
          display: flex;
          flex-wrap: wrap;

          .el-form-item {
            width: 50%;
          }
        }
      }
    }
    .preview {
      img {
        width: 100px;
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
  }
}
</style>
